import themeChangeBehavior from 'tdesign-miniprogram/mixins/theme-change';
const pagePermissionMixin = require('../../utils/page-permission-mixin.js');
const { MODULES } = require('../../utils/permission.js');
const { pageOptimizationMixin } = require('../../utils/page-optimization-mixin.js');
const {
  fetchPendingApprovals,
  fetchCheckedApprovals,
  approveRecord,
  rejectRecord,
  updateProcessRecord,
  getApprovalStatistics
} = require('../../utils/leader-approval-api.js');
const { getEmployees } = require('../../utils/user-api.js');

Page({
  behaviors: [themeChangeBehavior],
  
  // 混入权限检查方法和性能优化
  ...pagePermissionMixin,
  ...pageOptimizationMixin,
  
  data: {
    ...pageOptimizationMixin.data,
    userInfo: null,
    activeTab: 'pending', // pending, approved, rejected
    pendingList: [],
    approvedList: [],
    rejectedList: [],
    originalPendingList: [], // 保存原始数据用于筛选
    originalApprovedList: [],
    originalRejectedList: [],
    filterOptions: {
      quickTime: '',
      startDate: '',
      endDate: '',
      employee: '',
      product: ''
    },
    quickTimeOptions: [
      { label: '今天', value: 'today' },
      { label: '昨天', value: 'yesterday' },
      { label: '本周', value: 'thisWeek' },
      { label: '上周', value: 'lastWeek' },
      { label: '本月', value: 'thisMonth' },
      { label: '上月', value: 'lastMonth' }
    ],
    filteredResultText: '',
    hasActiveFilter: false,
    showFilterDialog: false,
    showEditDialog: false,
    showRemarkDialog: false,
    editFormData: {
      id: '',
      productCode: '',
      processCode: '',
      quantity: ''
    },
    remarkFormData: {
      id: '',
      action: '', // 'approve' or 'reject'
      remark: ''
    },
    statistics: {
      pendingCount: 0,
      approvedCount: 0, 
      rejectedCount: 0,
      todayApproved: 0
    },
    loading: false,
    refreshing: false,
    employees: [],  // 组员列表
    employeeOptions: [{ label: '全部员工', value: '' }],  // 员工选择器选项
    selectedEmployeeIndex: 0,  // 选中的员工索引
    selectedEmployeeLabel: '全部员工',  // 选中的员工显示名称
    loadingEmployees: false
  },

  onLoad() {
    // 使用优化的页面加载
    this.onLoadOptimized('leader-approval', () => {
      // 检查页面权限
      this.onPageLoadPermissionCheck(MODULES.LEADER_APPROVAL);
      
      // 调试：检查token状态
      const token = wx.getStorageSync('token');
      const userInfo = wx.getStorageSync('userInfo');
      
      // 加载关键数据
      this.loadEssentialData();
    });
  },

  onReady() {
    // 使用优化的页面准备完成
    this.onReadyOptimized(() => {
      this.loadSecondaryData();
    });
  },

  onShow() {
    // 使用优化的页面显示
    this.onShowOptimized(() => {
      this.refreshData();
    });
  },

  onUnload() {
    // 使用优化的页面卸载
    this.onUnloadOptimized();
  },

  // 加载关键数据
  async loadEssentialData() {
    try {
      // 先加载用户信息
      this.loadUserInfo();
      
      // 然后加载审批列表数据
      await this.loadAllData();
      
      // 关键数据加载完成
      this.markPageReady();
      
    } catch (error) {
      console.error('领导审批关键数据加载失败:', error);
      this.markPageError(error);
    }
  },

  // 加载次要数据
  loadSecondaryData() {
    // 延迟加载员工列表，不阻塞主要功能
    this.loadEmployees();
  },

  // 刷新数据
  refreshData() {
    this.loadAllData();
    this.loadEmployees();
  },

  loadUserInfo() {
    const userInfo = wx.getStorageSync('userInfo');
    this.setData({ userInfo });
  },

  async loadPendingRecords() {
    try {
      const result = await fetchPendingApprovals();
      
      if (result.success) {
        // 将API数据转换为页面需要的格式
        const pendingList = [];
        result.data.list.forEach(user => {
          user.products.forEach(product => {
            product.processes.forEach(process => {
              pendingList.push({
                id: process.id,
                employeeName: user.username,  // 修改为模板期望的字段名
                employeeId: user.account,
                employee: user.username,  // 保留原字段用于编辑时的data-employee
                productName: product.productName,  // 修改为模板期望的字段名
                product: product.productName,  // 保留原字段用于编辑时的data-product
                productCode: product.productCode,
                processName: process.processName,  // 添加模板需要的字段
                process: process.processName,  // 保留原字段
                processCode: process.processCode,
                quantity: process.quantity,
                unitPrice: process.price,
                amount: process.totalPrice,  // 修改为模板期望的字段名
                totalAmount: process.totalPrice,  // 保留原字段
                submitTime: this.formatDateTime(process.createTime),
                workDate: this.formatDateTime(process.createTime),  // 添加工作日期
                workHours: process.workHours || 0,  // 添加工时
                remark: process.remark,
                urgency: 'normal',
                status: process.status
              });
            });
          });
        });
        
        this.setData({ 
          pendingList,
          originalPendingList: [...pendingList] // 保存原始数据
        });
      } else {
        wx.showToast({
          title: result.message,
          icon: 'none'
        });
      }
    } catch (error) {
      wx.showToast({
        title: '加载待审核数据失败',
        icon: 'none'
      });
    }
  },

  async loadApprovedRecords() {
    try {
      const result = await fetchCheckedApprovals();
      
      if (result.success) {
        // 将API数据转换为页面需要的格式
        const approvedList = [];
        result.data.list.forEach(user => {
          user.products.forEach(product => {
            product.processes.forEach(process => {
              approvedList.push({
                id: process.id,
                employeeName: user.username,  // 修改为模板期望的字段名
                employeeId: user.account,
                employee: user.username,  // 保留原字段
                productName: product.productName,  // 修改为模板期望的字段名
                product: product.productName,  // 保留原字段
                productCode: product.productCode,
                processName: process.processName,  // 添加模板需要的字段
                process: process.processName,  // 保留原字段
                processCode: process.processCode,
                quantity: process.quantity,
                unitPrice: process.price,
                amount: process.totalPrice,  // 修改为模板期望的字段名
                totalAmount: process.totalPrice,  // 保留原字段
                submitTime: this.formatDateTime(process.createTime),
                workDate: this.formatDateTime(process.createTime),  // 添加工作日期
                workHours: process.workHours || 0,  // 添加工时
                approveTime: this.formatDateTime(process.createTime),
                remark: process.remark,
                approver: this.data.userInfo?.name || '组长',
                status: process.status
              });
            });
          });
        });
        
        this.setData({ 
          approvedList,
          originalApprovedList: [...approvedList] // 保存原始数据
        });
      } else {
        wx.showToast({
          title: result.message,
          icon: 'none'
        });
      }
    } catch (error) {
      wx.showToast({
        title: '加载已审核数据失败',
        icon: 'none'
      });
    }
  },

  async loadAllData() {
    this.setData({ loading: true });
    
    try {
      // 并行加载所有数据
      await Promise.all([
        this.loadPendingRecords(),
        this.loadApprovedRecords(),
        this.loadRejectedRecords(),
        this.loadStatistics()
      ]);
      
      return Promise.resolve();
    } catch (error) {
      wx.showToast({
        title: '数据加载失败',
        icon: 'none'
      });
      return Promise.reject(error);
    } finally {
      this.setData({ loading: false });
    }
  },

  async loadRejectedRecords() {
    try {
      const { getRejectedRecords } = require('../../utils/leader-approval-api.js');
      const result = await getRejectedRecords();
      
      if (result.success) {

        
        // 将API数据转换为页面需要的格式
        const rejectedList = [];
        result.data.list.forEach(user => {
          user.products.forEach(product => {
            product.processes.forEach(process => {
              rejectedList.push({
                id: process.id,
                employeeName: user.username,  // 修改为模板期望的字段名
                employeeId: user.account,
                employee: user.username,  // 保留原字段
                productName: product.productName,  // 修改为模板期望的字段名
                product: product.productName,  // 保留原字段
                productCode: product.productCode,
                processName: process.processName,  // 添加模板需要的字段
                processCode: process.processCode,
                quantity: process.quantity,
                unitPrice: process.price,
                amount: process.totalPrice,  // 修改为模板期望的字段名
                totalAmount: process.totalPrice,  // 保留原字段
                workDate: this.formatDateTime(process.createTime),  // 添加工作日期
                workHours: process.workHours || 0,  // 添加工时
                rejectTime: this.formatDateTime(user.rejectTime || process.createTime),
                rejectReason: process.rejectReason || '无拒绝原因',
                remark: process.remark,
                status: process.status
              });
            });
          });
        });
  
        this.setData({ 
          rejectedList,
          originalRejectedList: [...rejectedList] // 保存原始数据用于搜索
        });
        
        // 重新加载统计数据
        this.loadStatistics();
      } else {

        this.setData({ 
          rejectedList: [],
          originalRejectedList: []
        });
        
        wx.showToast({
          title: result.message || '加载失败',
          icon: 'none'
        });
      }
    } catch (error) {

      this.setData({ 
        rejectedList: [],
        originalRejectedList: []
      });
      
      wx.showToast({
        title: '网络错误，请重试',
        icon: 'none'
      });
    }
  },

  async loadStatistics() {
    try {
      const result = await require('../../utils/leader-approval-api.js').getApprovalStatistics();
      
      if (result.success) {
        this.setData({ statistics: result.data });
      } else {
        console.warn('⚠️ 获取统计数据失败，使用本地数据');
        // 使用本地数据作为备选
        const statistics = {
          pendingCount: this.data.pendingList.length,
          approvedCount: this.data.approvedList.length,
          rejectedCount: this.data.rejectedList.length,
          todayApproved: 0
        };
        this.setData({ statistics });
      }
    } catch (error) {
      console.error('❌ 加载统计数据异常:', error);
      // 使用本地数据作为备选
      const statistics = {
        pendingCount: this.data.pendingList.length,
        approvedCount: this.data.approvedList.length,
        rejectedCount: this.data.rejectedList.length,
        todayApproved: 0
      };
      this.setData({ statistics });
    }
  },

  onTabChange(e) {
    const { value } = e.detail;
    this.setData({ activeTab: value });
  },

  onApprove(e) {
    const { id } = e.currentTarget.dataset;
    
    wx.showModal({
      title: '通过审核',
      content: '请输入通过备注',
      editable: true,
      placeholderText: '请输入通过备注...',
      success: (res) => {
        if (res.confirm) {
          const remark = res.content ? res.content.trim() : '通过';
          this.approveRecord(id, remark);
        }
      }
    });
  },

  onReject(e) {
    const { id } = e.currentTarget.dataset;
    
    wx.showModal({
      title: '拒绝原因',
      content: '请输入拒绝原因',
      editable: true,
      placeholderText: '请输入拒绝原因...',
      success: (res) => {
        if (res.confirm && res.content.trim()) {
          this.rejectRecord(id, res.content.trim());
        } else if (res.confirm && !res.content.trim()) {
          wx.showToast({
            title: '请输入拒绝原因',
            icon: 'none'
          });
        }
      }
    });
  },

  async approveRecord(id, remark = '') {
    wx.showLoading({ title: '处理中...' });
    
    try {
      const result = await require('../../utils/leader-approval-api.js').approveRecord(id, remark);
      
      wx.hideLoading();
      
      if (result.message == "操作成功") {
        wx.showToast({
          title: result.message,
          icon: 'success'
        });
        
        // 刷新数据
        this.loadAllData().then(() => {
          // 如果有筛选条件，重新应用筛选
          if (this.data.hasActiveFilter) {
            this.applyFilter();
          }
        });
      } else {
        wx.showToast({
          title: result.message,
          icon: 'none'
        });
      }
    } catch (error) {
      wx.hideLoading();
      wx.showToast({
        title: '操作失败',
        icon: 'none'
      });
    }
  },

  async rejectRecord(id, reason) {
    wx.showLoading({ title: '处理中...' });
    
    try {
      const result = await require('../../utils/leader-approval-api.js').rejectRecord(id, reason);
      
      wx.hideLoading();
      
      if (result.message == "操作成功") {
        wx.showToast({
          title: result.message,
          icon: 'success'
        });
        
        // 刷新数据
        this.loadAllData().then(() => {
          // 如果有筛选条件，重新应用筛选
          if (this.data.hasActiveFilter) {
            this.applyFilter();
          }
        });
      } else {
        wx.showToast({
          title: result.message,
          icon: 'none'
        });
      }
    } catch (error) {
      wx.hideLoading();
      wx.showToast({
        title: '操作失败',
        icon: 'none'
      });
    }
  },

  // 显示修改对话框
  onEdit(e) {
    const dataset = e.currentTarget.dataset;
    const { id, productCode, processCode, quantity, employee, product } = dataset;
    
    // 检查必需参数
    if (!id || !productCode || !processCode || !quantity) {
      wx.showModal({
        title: '数据错误',
        content: `获取记录信息失败\nID: ${id}\n产品代码: ${productCode}\n工序代码: ${processCode}\n数量: ${quantity}`,
        showCancel: false
      });
      return;
    }
    
    // 确保所有参数都是string类型
    const formData = {
      id: String(id),
      productCode: String(productCode),
      processCode: String(processCode),
      quantity: String(quantity)
    };
    
    this.setData({
      showEditDialog: true,
      editFormData: formData
    });
  },

  onShowFilter() {
    // 更新筛选结果文本
    const { pendingList, approvedList, rejectedList, originalPendingList, originalApprovedList, originalRejectedList } = this.data;
    const currentTotal = pendingList.length + approvedList.length + rejectedList.length;
    const originalTotal = originalPendingList.length + originalApprovedList.length + originalRejectedList.length;
    
    let filteredResultText = '';
    if (currentTotal !== originalTotal) {
      filteredResultText = `筛选到 ${currentTotal} 条记录，共 ${originalTotal} 条`;
    }
    
    this.setData({ 
      showFilterDialog: true,
      filteredResultText
    });
  },

  onFilterConfirm() {
    this.applyFilter();
    this.setData({ showFilterDialog: false });
    wx.showToast({
      title: '筛选已应用',
      icon: 'success'
    });
  },

  onFilterCancel() {
    this.setData({ showFilterDialog: false });
  },

  // 快捷时间段选择
  onQuickTimeSelect(e) {
    const { value } = e.currentTarget.dataset;
    const dateRange = this.getDateRangeFromQuickTime(value);
    
    this.setData({
      'filterOptions.quickTime': value,
      'filterOptions.startDate': dateRange.startDate,
      'filterOptions.endDate': dateRange.endDate
    });
  },

  // 开始日期选择
  onStartDateChange(e) {
    this.setData({
      'filterOptions.startDate': e.detail.value,
      'filterOptions.quickTime': '' // 清空快捷选择
    });
  },

  // 结束日期选择
  onEndDateChange(e) {
    this.setData({
      'filterOptions.endDate': e.detail.value,
      'filterOptions.quickTime': '' // 清空快捷选择
    });
  },

  onEmployeePickerChange(e) {
    const index = parseInt(e.detail.value);
    const selectedOption = this.data.employeeOptions[index];
    
    this.setData({
      selectedEmployeeIndex: index,
      selectedEmployeeLabel: selectedOption.label,
      'filterOptions.employee': selectedOption.value
    });
  },

  onFilterProductInput(e) {
    this.setData({
      'filterOptions.product': e.detail.value
    });
  },

  // 清空筛选条件
  onClearFilter() {
    this.setData({
      'filterOptions.quickTime': '',
      'filterOptions.startDate': '',
      'filterOptions.endDate': '',
      'filterOptions.employee': '',
      'filterOptions.product': '',
      selectedEmployeeIndex: 0,
      selectedEmployeeLabel: '全部员工',
      filteredResultText: '',
      hasActiveFilter: false
    });
    
    // 恢复原始数据和统计信息
    this.setData({
      pendingList: [...this.data.originalPendingList],
      approvedList: [...this.data.originalApprovedList],
      rejectedList: [...this.data.originalRejectedList],
      'statistics.pendingCount': this.data.originalPendingList.length,
      'statistics.approvedCount': this.data.originalApprovedList.length,
      'statistics.rejectedCount': this.data.originalRejectedList.length
    });
    
    wx.showToast({
      title: '筛选已清空',
      icon: 'success'
    });
  },

  // 根据快捷时间段获取日期范围
  getDateRangeFromQuickTime(quickTime) {
    const now = new Date();
    const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
    
    let startDate, endDate;
    
    switch (quickTime) {
      case 'today':
        startDate = endDate = this.formatDate(today);
        break;
      case 'yesterday':
        const yesterday = new Date(today.getTime() - 24 * 60 * 60 * 1000);
        startDate = endDate = this.formatDate(yesterday);
        break;
      case 'thisWeek':
        const thisWeekStart = new Date(today.getTime() - (today.getDay() || 7) * 24 * 60 * 60 * 1000);
        startDate = this.formatDate(thisWeekStart);
        endDate = this.formatDate(today);
        break;
      case 'lastWeek':
        const lastWeekEnd = new Date(today.getTime() - (today.getDay() || 7) * 24 * 60 * 60 * 1000 - 24 * 60 * 60 * 1000);
        const lastWeekStart = new Date(lastWeekEnd.getTime() - 6 * 24 * 60 * 60 * 1000);
        startDate = this.formatDate(lastWeekStart);
        endDate = this.formatDate(lastWeekEnd);
        break;
      case 'thisMonth':
        const thisMonthStart = new Date(now.getFullYear(), now.getMonth(), 1);
        startDate = this.formatDate(thisMonthStart);
        endDate = this.formatDate(today);
        break;
      case 'lastMonth':
        const lastMonthStart = new Date(now.getFullYear(), now.getMonth() - 1, 1);
        const lastMonthEnd = new Date(now.getFullYear(), now.getMonth(), 0);
        startDate = this.formatDate(lastMonthStart);
        endDate = this.formatDate(lastMonthEnd);
        break;
      default:
        startDate = endDate = '';
    }
    
    return { startDate, endDate };
  },

  // 格式化日期为YYYY-MM-DD格式
  formatDate(date) {
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    return `${year}-${month}-${day}`;
  },

  // 应用筛选
  applyFilter() {
    const { startDate, endDate, employee, product } = this.data.filterOptions;
    
    // 筛选待审核列表
    let filteredPending = [...this.data.originalPendingList];
    let filteredApproved = [...this.data.originalApprovedList];
    let filteredRejected = [...this.data.originalRejectedList];
    
    // 按时间筛选
    if (startDate || endDate) {
      filteredPending = this.filterByDate(filteredPending, startDate, endDate);
      filteredApproved = this.filterByDate(filteredApproved, startDate, endDate);
      filteredRejected = this.filterByDate(filteredRejected, startDate, endDate);
    }
    
    // 按员工姓名筛选（选择器模式，精确匹配）
    if (employee.trim()) {
      const employeeFilter = employee.trim();
      filteredPending = filteredPending.filter(item => 
        item.employee === employeeFilter || item.employeeName === employeeFilter
      );
      filteredApproved = filteredApproved.filter(item => 
        item.employee === employeeFilter || item.employeeName === employeeFilter
      );
      filteredRejected = filteredRejected.filter(item => 
        item.employee === employeeFilter || item.employeeName === employeeFilter
      );
    }
    
    // 按产品名称筛选
    if (product.trim()) {
      const productFilter = product.trim().toLowerCase();
      filteredPending = filteredPending.filter(item => 
        item.product.toLowerCase().includes(productFilter)
      );
      filteredApproved = filteredApproved.filter(item => 
        item.product.toLowerCase().includes(productFilter)
      );
      filteredRejected = filteredRejected.filter(item => 
        item.product.toLowerCase().includes(productFilter)
      );
    }
    
    // 更新筛选结果文本
    const totalFiltered = filteredPending.length + filteredApproved.length + filteredRejected.length;
    const originalTotal = this.data.originalPendingList.length + this.data.originalApprovedList.length + this.data.originalRejectedList.length;
    const filteredResultText = `筛选到 ${totalFiltered} 条记录，共 ${originalTotal} 条`;
    
    // 检查是否有筛选条件生效
    const hasActiveFilter = !!(startDate || endDate || employee.trim() || product.trim());
    
    this.setData({
      pendingList: filteredPending,
      approvedList: filteredApproved,
      rejectedList: filteredRejected,
      filteredResultText,
      hasActiveFilter,
      'statistics.pendingCount': filteredPending.length,
      'statistics.approvedCount': filteredApproved.length,
      'statistics.rejectedCount': filteredRejected.length
    });
  },

  // 按日期范围筛选数据
  filterByDate(list, startDate, endDate) {
    if (!startDate && !endDate) return list;
    
    return list.filter(item => {
      const itemDate = this.extractDateFromTime(item.submitTime || item.approveTime || item.rejectTime);
      if (!itemDate) return true;
      
      if (startDate && itemDate < startDate) return false;
      if (endDate && itemDate > endDate) return false;
      return true;
    });
  },

  // 从时间字符串中提取日期部分
  extractDateFromTime(timeString) {
    if (!timeString) return '';
    
    // 处理格式：2024-01-01 12:00 或 2024-01-01T12:00:00
    const match = timeString.match(/(\d{4}-\d{2}-\d{2})/);
    return match ? match[1] : '';
  },

    onBatchApprove() {
    if (this.data.pendingList.length === 0) {
      wx.showToast({
        title: '没有待核对记录',
        icon: 'none'
      });
      return;
    }
    
    wx.showModal({
      title: '批量通过',
      content: '请输入批量通过备注',
      editable: true,
      placeholderText: '请输入批量通过备注...',
      success: (res) => {
        if (res.confirm) {
          const remark = res.content ? res.content.trim() : '批量通过';
          this.batchApproveRecords(remark);
        }
      }
    });
  },

  async batchApproveRecords(remark = '批量通过') {
    wx.showLoading({ title: '批量处理中...' });
    
    try {
      const promises = this.data.pendingList.map(record => 
        require('../../utils/leader-approval-api.js').approveRecord(record.id, remark)
      );
      
      const results = await Promise.all(promises);
      
      // 检查是否所有请求都成功
      const failedCount = results.filter(result => !result.message == "操作成功").length;
      const successCount = results.length - failedCount;
      
      wx.hideLoading();
      
      if (failedCount === 0) {
        wx.showToast({
          title: `批量通过${successCount}条记录`,
          icon: 'success'
        });
      } else {
        wx.showToast({
          title: `成功${successCount}条，失败${failedCount}条`,
          icon: 'none'
        });
      }
      
      // 刷新数据
      this.loadAllData().then(() => {
        // 如果有筛选条件，重新应用筛选
        if (this.data.hasActiveFilter) {
          this.applyFilter();
        }
      });
      
    } catch (error) {
      wx.hideLoading();
      wx.showToast({
        title: '批量处理失败',
        icon: 'none'
      });
    }
  },

  // 加载组员列表
  async loadEmployees() {
    if (this.data.loadingEmployees) return;
    
    this.setData({ loadingEmployees: true });
    
    try {
      const result = await getEmployees();
      
      if (result.message === "操作成功") {
        
        // 为筛选器准备数据，添加"全部"选项
        const employeeOptions = [
          { label: '全部员工', value: '' },
          ...result.data.map(emp => ({
            label: emp.name || emp.employeeName || '未知姓名',
            value: emp.name || emp.employeeName || '未知姓名'
          }))
        ];
        
        
        this.setData({ 
          employees: result.data || [],
          employeeOptions: employeeOptions
        });
        
      } else {

        this.setData({ 
          employees: [],
          employeeOptions: [{ label: '全部员工', value: '' }]
        });
      }
    } catch (error) {

      this.setData({ 
        employees: [],
        employeeOptions: [{ label: '全部员工', value: '' }]
      });
    } finally {
      this.setData({ loadingEmployees: false });
    }
  },

  formatDateTime(dateString) {
    if (!dateString) return '';
    const date = new Date(dateString);
    return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
  },

  // 提交审批
  async submitApproval() {
    const { id, action, remark } = this.data.remarkFormData;
    
    if (!remark.trim() && action === 'reject') {
      wx.showToast({
        title: '请输入拒绝原因',
        icon: 'none'
      });
      return;
    }

    if (action === 'approve') {
      await this.approveRecord(id, remark);
    } else {
      await this.rejectRecord(id, remark);
    }
    
    this.setData({ showRemarkDialog: false });
  },

  // 提交编辑
  async submitEdit() {
    const { id, productCode, processCode, quantity } = this.data.editFormData;
    
    // 检查token
    const token = wx.getStorageSync('token');
    
    if (!token) {
      wx.showToast({
        title: '未登录，请先登录',
        icon: 'none'
      });
      return;
    }
    
    if (!quantity || isNaN(quantity) || parseInt(quantity) <= 0) {
      wx.showToast({
        title: '请输入有效数量',
        icon: 'none'
      });
      return;
    }

    // 验证必需参数
    if (!id || !productCode || !processCode) {
      wx.showToast({
        title: '缺少必需参数',
        icon: 'none'
      });
      return;
    }

    wx.showLoading({ title: '保存中...' });

    try {
      // 确保所有参数都是string类型
      const updateData = {
        id: String(id),
        productCode: String(productCode),
        processCode: String(processCode),
        quantity: String(quantity)
      };
      
      const result = await require('../../utils/leader-approval-api.js').updateProcessRecord(updateData);

      wx.hideLoading();

      if (result.message == "操作成功") {
        wx.showToast({
          title: result.message,
          icon: 'success'
        });
        
        this.setData({ showEditDialog: false });
        // 刷新数据
        this.loadAllData().then(() => {
          // 如果有筛选条件，重新应用筛选
          if (this.data.hasActiveFilter) {
            this.applyFilter();
          }
        });
      } else {
        wx.showToast({
          title: result.message || '修改失败',
          icon: 'none'
        });
      }
    } catch (error) {
      wx.hideLoading();

      
      // 显示详细的错误信息
      wx.showModal({
        title: '修改失败',
        content: `错误信息: ${error.message || '未知错误'}\n错误代码: ${error.code || '无代码'}`,
        showCancel: false
      });
    }
  },

  // 表单输入处理
  onRemarkInput(e) {
    this.setData({
      'remarkFormData.remark': e.detail.value
    });
  },

  onQuantityInput(e) {
    this.setData({
      'editFormData.quantity': e.detail.value
    });
  },

  // 对话框控制
  onCloseRemarkDialog() {
    this.setData({ showRemarkDialog: false });
  },

  onCloseEditDialog() {
    this.setData({ showEditDialog: false });
  },

  // 下拉刷新
  async onPullDownRefresh() {
    this.setData({ refreshing: true });
    await this.loadAllData();
    this.setData({ refreshing: false });
    wx.stopPullDownRefresh();
  }
}); 